package com.baozun.houji.order.fragment

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import com.baozhun.mall.common.base.BaseListFragment
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.databinding.FragmentBaseListBinding
import com.baozhun.mall.common.ext.loadArrayListData
import com.baozhun.mall.common.ext.showToast
import com.baozun.houji.order.R
import com.baozun.houji.order.activity.OrderDetailActivity
import com.baozun.houji.order.adapter.OrderListAdapter
import com.baozhun.mall.common.model.bean.OrderInfoBean
import com.baozhun.mall.common.widget.EmptyView
import com.baozun.houji.order.activity.RefundDetailActivity
import com.baozhun.mall.common.model.enums.OrderStatus
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.util.eventbus.EventMessage
import com.baozun.houji.order.util.order.OrderActionFinishListener
import com.baozun.houji.order.util.order.enums.OrderActionType
import com.baozun.houji.order.viewmodel.OrderListViewModel
import com.baozun.houji.order.databinding.ItemOrderListBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import me.hgj.jetpackmvvm.ext.util.copyToClipboard
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @Title：订单列表
 * @Description：
 * @Author：luoxing
 * @Since：2022/11/20
 * @Version：1.0.0
 */
class OrderListFragment :
    BaseListFragment<OrderListViewModel, FragmentBaseListBinding, ItemOrderListBinding, OrderInfoBean>(),
    OnItemChildClickListener, OrderActionFinishListener {
    private var mTimer: CountDownTimer? = null
    private val mListAdapter: OrderListAdapter by lazy { OrderListAdapter(arrayListOf(), this) }
    private val orderStatus by lazy { arguments?.getSerializable(Constants.Order.ORDER_STATUS) as OrderStatus }
    private val isAfterSaleOrder by lazy { arguments?.getBoolean(Constants.Order.IS_AFTER_SALE_ORDER) }
    private val mIsSearchOrder by lazy { arguments?.getBoolean(Constants.Order.IS_SEARCH_ORDER) }
    private val isIntegralReturnOrder by lazy { arguments?.getBoolean(Constants.Order.INTEGRAL_RETURN_RELATED_ORDER) }
    private val billId by lazy { arguments?.getString(Constants.Order.INTEGRAL_RETURN_BILL_ID) }
    private var mSearchKey: String? = null

    companion object {
        fun newInstance(orderStatus: OrderStatus, isAfterSaleOrder: Boolean = false, isSearchOrder: Boolean = false): OrderListFragment {
            return newInstance(orderStatus, isAfterSaleOrder, isSearchOrder, false, "")
        }

        fun newInstance(orderStatus: OrderStatus, isAfterSaleOrder: Boolean = false, isSearchOrder: Boolean = false, isIntegralReturnOrder: Boolean = false, billId: String): OrderListFragment {
            return OrderListFragment().apply {
                arguments = Bundle().apply {
                    putSerializable(Constants.Order.ORDER_STATUS, orderStatus)
                    putSerializable(Constants.Order.IS_AFTER_SALE_ORDER, isAfterSaleOrder)
                    putSerializable(Constants.Order.IS_SEARCH_ORDER, isSearchOrder)
                    putBoolean(Constants.Order.INTEGRAL_RETURN_RELATED_ORDER, isIntegralReturnOrder)
                    putString(Constants.Order.INTEGRAL_RETURN_BILL_ID, billId)
                }
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        EventBusUtils.register(this)
    }

    /**
     * 搜索订单
     */
    fun searchOrder(search: String? = null) {
        mSearchKey = search
        loadData(true)
    }

    override fun loadData(isRefresh: Boolean) {
        if (isAfterSaleOrder == true) {
            mViewModel.getAfterSaleList(isRefresh)
        }  else {
            if (isSearchInit()) return //搜索首次加载不显示数据
            mViewModel.getOrderList(isRefresh, orderStatus.status, mSearchKey)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.mOrderList.observe(this) { it ->
            if (it.current_page == 1 && !isSearchInit())
                mListAdapter.setEmptyView(
                    EmptyView.Builder(mActivity).emptyHintText(if (mIsSearchOrder == true) com.baozhun.mall.res.R.string.no_order_search_data_hint else com.baozhun.mall.res.R.string.no_order_data_hint)
                        .build()
                )
            loadArrayListData(it, mListAdapter, mDataBinding.baseRefreshRv)
//            if (it.data.filter { it.order_status == OrderStatus.WAIT_DELIVERY.status }.isNotNull())
//                startCountDownTimer()
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        when (view?.id) {
            R.id.tv_copy -> {
                context?.copyToClipboard(mListAdapter.getItem(position).order_no)
                showToast(com.baozhun.mall.res.R.string.alr_copy)
            }
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        super.onItemClick(adapter, view, position)
        if (isAfterSaleOrder == true) {
            RefundDetailActivity.start(mActivity, mListAdapter.getItem(position).after_sale_no)
        } else {
            OrderDetailActivity.start(mActivity, mListAdapter.getItem(position).order_no)
        }
    }

    override fun createAdapter(): BaseQuickAdapter<OrderInfoBean, BaseDataBindingHolder<ItemOrderListBinding>>? {
        return mListAdapter
    }

    /**
     * 开始倒计时
     */
    private fun startCountDownTimer() {
        mTimer?.cancel()
        mTimer = object : CountDownTimer(Long.MAX_VALUE, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                mListAdapter.updatePaySurplusTime()
            }

            override fun onFinish() {
            }

        }
        mTimer?.start()
    }

    override fun reload(orderActionType: OrderActionType?) {
        loadData(true)
        if ((orderActionType == OrderActionType.IMME_PAY || orderActionType == OrderActionType.CANCEL_ORDER) && (orderStatus == OrderStatus.ALL || orderStatus == OrderStatus.WAIT_DELIVERY)) { //非全部订单列表操作完之后刷新全部订单列表里的状态
            EventBusUtils.sendEvent(eventCode = EventCode.REFRESH_ORDER_STATUS)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage<Any>) {
        if (event.eventCode == EventCode.REFRESH_ORDER_STATUS && (orderStatus == OrderStatus.ALL || orderStatus == OrderStatus.WAIT_DELIVERY)) {
            loadData(true)
        }
    }

    override fun startOrderDetail(orderId: String) {
        OrderDetailActivity.start(mActivity, orderId = orderId)
    }

    override fun startRefundDetail(refundNo: String) {
        RefundDetailActivity.start(mActivity, refundNo)
    }


    override fun onDestroy() {
        super.onDestroy()
        mTimer?.cancel()
    }

    override fun getDividerSize(): Int {
        return 8
    }

    override fun useFragmentViewModelStoreOwner(): Boolean {
        return true
    }

    /**
     * 是否为搜索首次进入
     */
    private fun isSearchInit(): Boolean {
        return mSearchKey.isNullOrEmpty() && mIsSearchOrder == true
    }
}